package openhaven.control.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import org.apache.log4j.Logger;

public class ReceiveWorker implements Runnable
{
    private final DatagramSocket socket;
    private static final Logger LOG = Logger.getLogger(ReceiveWorker.class);

    public ReceiveWorker(final DatagramSocket socket, final InetAddress host, final String username, final byte[] cookie)
    {
        this.socket = socket;
    }

    @Override
    public void run()
    {
        boolean alive = true;
        try
        {
            socket.setSoTimeout(1000);
        }
        catch (final SocketException e)
        {
            throw (new RuntimeException(e));
        }
        while (alive)
        {
            try
            {
                final DatagramPacket p = receivePacket();
                final Message msg = new Message(p.getData()[0], p.getData(), 1, p.getLength() - 1);
                LOG.debug("RWorker got message: " + Message.messageTypeBinding.get(msg.type));
            }
            catch (final IOException e)
            {
                e.printStackTrace();
                alive = false;
            }
        }
    }

    private DatagramPacket receivePacket() throws IOException
    {
        final DatagramPacket p = new DatagramPacket(new byte[65536], 65536);
        socket.receive(p);
        return p;
    }
}
